#!/usr/bin/env python

import sys
import smtplib
import email.MIMEText
import string
import getpass
import getopt

class GmailSender:
    def __init__(self, username, password):
        self.server = smtplib.SMTP('smtp.gmail.com',587)
        #server.set_debuglevel(1)
        self.server.ehlo()
        self.server.starttls()
        self.server.ehlo()
        self.server.login(username, password)

    def send(self, fromAddress, toAddresses, message):
        self.server.sendmail(fromAddress, toAddresses, message)

    def quit(self):
        self.server.quit()
        
def main(args=None):
    if args == None:
        args = sys.argv[1:]
    (opts, args) = getopt.getopt(args, 's:')
    print opts, args

    subject = 'No subject'
    for (key, value) in opts:
        if key == '-s':
            subject = value
    password = getpass.getpass('Password: ')

    body = sys.stdin.read()
    gmail_me = 'blair.conrad@gmail.com'
    me = gmail_me
    to_addresses = args[0:]
    msg = email.MIMEText.MIMEText(body, 'plain')
    msg['Subject'] = subject
    msg['To'] = string.join(to_addresses, ', ')
    
    server = GmailSender(gmail_me, password)
    server.send(me, to_addresses, msg.as_string())
    server.quit()
    return 0

if __name__ == '__main__':
    sys.exit(main())

